package com.health.life.utils;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.health.life.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;


public class DBUtil {

    private static final String PACKNAME="com.health.life";
    private static final String DATABASE_PATH = "/data/data/"+PACKNAME+"/databases";

    private static final int DATABASE_VERSION = 0;

    private static final String DATABASE_NAME = "cook.db";

    private static final String outFileName = DATABASE_PATH + "/" + DATABASE_NAME;
    private final Context context;


    private static SQLiteDatabase database;



    public DBUtil(Context context)
    {
        this.context=context;
    }


    public static SQLiteDatabase getInstance() {
        if (database==null)
        database = SQLiteDatabase.openOrCreateDatabase(outFileName, null);
        return database;
    }

    public void copyDB(){
        File file = new File(outFileName);
        if (file.exists()) {
            database = SQLiteDatabase.openOrCreateDatabase(outFileName, null);
            if (database.getVersion() != DATABASE_VERSION) {
                database.close();
                file.delete();
            }
        }
        try {
            buildDatabase();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*****
     * 创建数据库
     * @throws Exception
     */
    private void buildDatabase() throws Exception {
        InputStream myInput = context.getResources().openRawResource(R.raw.cook);
//        InputStream myInput = context.getResources().getAssets().open(DATABASE_NAME);
        if (myInput==null){
            myInput = context.getAssets().open(DATABASE_NAME);
        }
        File file = new File(outFileName);

        File dir = new File(DATABASE_PATH);
        if (!dir.exists()) {
            if (!dir.mkdir()) {
                throw new Exception("创建失败");
            }
        }

        if (!file.exists()) {
            try {
                OutputStream myOutput = new FileOutputStream(outFileName);

                byte[] buffer = new byte[1024];
                int length;
                while ((length = myInput.read(buffer)) > 0) {
                    myOutput.write(buffer, 0, length);
                }
                myOutput.close();
                myInput.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


}

